<!-- 部门管理 -->
<template>
  <div class="department-management">
    <div class="title-section">
      <h2>部门管理</h2>
      <button class="btn-primary" @click="openCreate">新建</button>
    </div>

    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>关键词</label>
          <input type="text" placeholder="请输入关键词" v-model="query.keyword">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model.number="query.status">
            <option value="">请选择</option>
            <option :value="1">启用</option>
            <option :value="0">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
          <th>部门编号</th>
          <th>部门名称</th>
          <th>部门描述</th>
          <th>部门负责人/班组长</th>
          <th>员工数</th>
          <th>启用状态</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, idx) in tableData" :key="row.departmentId || row.uid || idx">
          <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
          <td class="link-style" @click="openDetail(row)">{{ row.code }}</td>
          <td>{{ row.name }}</td>
          <td>{{ row.desc }}</td>
          <td>{{ row.leader }}</td>
          <td>{{ row.userCount }}</td>
          <td :class="{ 'status-enable': row.status === 1, 'status-disable': row.status !== 1 }">{{ row.statusText }}</td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportSelected">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        <select v-model.number="pageSize" @change="onPageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
        </select>
      </div>
    </div>
  </div>

  <!-- 部门详情抽屉 -->
  <div v-if="detailDrawerVisible" class="drawer-mask" @click.self="closeDetail">
    <div class="drawer">
      <div class="drawer-header">
        <div>部门详情</div>
        <div class="drawer-actions">
          <div class="more" @click.stop="toggleMoreMenu">⋯</div>
          <div v-if="moreMenuVisible" class="menu" @click.stop>
            <div class="menu-item" @click="onEditFromDetail">编辑</div>
            <div class="menu-item danger" @click="onDeleteFromDetail">删除</div>
          </div>
          <button class="btn-secondary" @click="closeDetail">关闭</button>
        </div>
      </div>
      <div class="drawer-body">
        <div class="detail-grid">
          <div class="item"><div class="label">部门编号</div><div class="value">{{ detail.code }}</div></div>
          <div class="item"><div class="label">部门名称</div><div class="value">{{ detail.name || '—' }}</div></div>
          <div class="item"><div class="label">负责人</div><div class="value">{{ detail.leader || '—' }}</div></div>
          <div class="item"><div class="label">员工数</div><div class="value">{{ detail.userCount ?? '—' }}</div></div>
          <div class="item"><div class="label">启用状态</div><div class="value" :class="{ 'status-enable': detail.status === 1, 'status-disable': detail.status !== 1 }">{{ detail.statusText }}</div></div>
          <div class="item item-span"><div class="label">部门描述</div><div class="value">{{ detail.desc || '—' }}</div></div>
        </div>
      </div>
    </div>
  </div>

  <!-- 新建部门弹窗 -->
  <div v-if="createDialogVisible" class="dialog-mask">
    <div class="dialog">
      <div class="dialog-header">新建部门</div>
      <div class="dialog-body">
        <div class="form-row">
          <label>部门名称<span class="req">*</span></label>
          <input v-model.trim="createForm.departmentName" placeholder="请输入部门名称">
          <div v-if="errors.departmentName" class="err">{{ errors.departmentName }}</div>
        </div>
        <div class="form-row">
          <label>部门描述</label>
          <input v-model.trim="createForm.departmentDesc" placeholder="请输入部门描述">
        </div>
        <div class="form-row">
          <label>员工数</label>
          <input v-model.number="createForm.employeeCount" type="number" min="0" placeholder="0">
          <div v-if="errors.employeeCount" class="err">{{ errors.employeeCount }}</div>
        </div>
        <div class="form-row">
          <label>负责人</label>
          <select v-model.number="createForm.uid">
            <option :value="null">不选择</option>
            <option v-for="u in userOptions" :key="u.value" :value="u.value">{{ u.label }}</option>
          </select>
        </div>
        <div class="form-row">
          <label>状态<span class="req">*</span></label>
          <select v-model.number="createForm.status">
            <option value="">请选择</option>
            <option :value="1">启用</option>
            <option :value="0">停用</option>
          </select>
          <div v-if="errors.status" class="err">{{ errors.status }}</div>
        </div>
      </div>
      <div class="dialog-footer">
        <button class="btn-secondary" @click="closeCreate" :disabled="createLoading">取消</button>
        <button class="btn-primary" @click="submitCreate" :disabled="createLoading">{{ createLoading ? '提交中...' : '提交' }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import { pageDepts, createDept, listUsers, updateDept, deleteDept } from '@/api/user'
import * as XLSX from 'xlsx'
export default {
  name: 'DepartmentManagement',
  data() {
    return {
      loading: false,
      selectAll: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPages: 1,
      query: { keyword: '', status: '' },
      tableData: [],
      createDialogVisible: false,
      createLoading: false,
      createForm: { departmentName: '', departmentDesc: '', employeeCount: 0, uid: null, status: '' },
      errors: {},
      userOptions: [],
      userLoading: false,
      detailDrawerVisible: false,
      detail: {},
      moreMenuVisible: false,
      isEditMode: false,
    }
  },
  created() { this.fetchData() },
  methods: {
    toggleMoreMenu() { this.moreMenuVisible = !this.moreMenuVisible },
    async openCreate() {
      this.createDialogVisible = true
      this.createForm = { departmentName: '', departmentDesc: '', employeeCount: 0, uid: null, status: '' }
      this.errors = {}
      await this.loadUsersForSelect()
    },
    closeCreate() { this.createDialogVisible = false },
    openDetail(row) {
      this.detail = { ...row }
      this.detailDrawerVisible = true
      this.moreMenuVisible = false
    },
    closeDetail() { this.detailDrawerVisible = false },
    async onEditFromDetail() {
      this.isEditMode = true
      this.moreMenuVisible = false
      this.createDialogVisible = true
      // 预填表单
      this.createForm = {
        departmentId: this.detail.departmentId,
        departmentName: this.detail.name || '',
        departmentDesc: this.detail.desc || '',
        employeeCount: Number(this.detail.userCount ?? 0),
        uid: this.detail.uid ?? null,
        status: this.detail.status,
      }
      this.errors = {}
      await this.loadUsersForSelect()
    },
    async onDeleteFromDetail() {
      this.moreMenuVisible = false
      if (!this.detail || !this.detail.departmentId) return
      if (!confirm('确认删除该部门吗？')) return
      try {
        await deleteDept(this.detail.departmentId)
        this.closeDetail()
        this.currentPage = 1
        await this.fetchData()
      } catch(e) { /* 全局拦截已提示 */ }
    },
    async fetchData() {
      try {
        this.loading = true
        const body = { pageNum: this.currentPage, pageSize: this.pageSize }
        if (this.query.keyword) body.keyword = this.query.keyword
        if (this.query.status !== '' && this.query.status !== null && this.query.status !== undefined) body.status = this.query.status
        const res = await pageDepts(body)
        const payload = res?.data
        const data = payload?.data || { total: 0, records: [] }
        this.total = Number(data.total || 0)
        this.totalPages = Math.max(1, Math.ceil(this.total / this.pageSize))
        this.tableData = (data.records || []).map(d => ({
          selected: false,
          departmentId: d.departmentId,
          code: String(d.departmentCode || '').replace(/_/g, ''),
          name: d.departmentName,
          desc: d.departmentDesc,
          leader: d.leaderName,
          userCount: d.employeeCount,
          status: d.status,
          statusText: d.status === 1 ? '启用' : '停用',
          uid: d.uid,
        }))
        this.updateSelectAll()
      } finally { this.loading = false }
    },
    validateCreate() {
      const errs = {}
      if (!this.createForm.departmentName) errs.departmentName = '请输入部门名称'
      if (this.createForm.status === '' || this.createForm.status === null || this.createForm.status === undefined) errs.status = '请选择状态'
      if (this.createForm.employeeCount != null && this.createForm.employeeCount !== '' && (isNaN(this.createForm.employeeCount) || this.createForm.employeeCount < 0)) {
        errs.employeeCount = '员工数必须为不小于0的数字'
      }
      this.errors = errs
      return Object.keys(errs).length === 0
    },
    async submitCreate() {
      if (!this.validateCreate()) return
      try {
        this.createLoading = true
        const base = {
          departmentName: this.createForm.departmentName,
          departmentDesc: this.createForm.departmentDesc,
          employeeCount: Number(this.createForm.employeeCount || 0),
          uid: this.createForm.uid ?? undefined,
          status: this.createForm.status,
        }
        if (this.isEditMode) {
          await updateDept({ departmentId: this.createForm.departmentId, ...base })
        } else {
          await createDept(base)
        }
        this.closeCreate()
        this.currentPage = 1
        await this.fetchData()
      } finally {
        this.createLoading = false
        this.isEditMode = false
      }
    },
    onSearch() { this.currentPage = 1; this.fetchData() },
    onReset() { this.query = { keyword: '', status: '' }; this.currentPage = 1; this.fetchData() },
    onPageSizeChange() { this.currentPage = 1; this.fetchData() },
    toggleSelectAll() { this.tableData.forEach(r => { r.selected = this.selectAll; }); },
    updateSelectAll() { this.selectAll = this.tableData.length > 0 && this.tableData.every(r => r.selected); },
    prevPage() { if (this.currentPage > 1) { this.currentPage--; this.fetchData() } },
    nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.fetchData() } },
    goToPage(page) { if (page !== this.currentPage) { this.currentPage = page; this.fetchData() } },
    exportSelected() {
      const selected = this.tableData.filter(r => r.selected)
      if (!selected.length) {
        alert('请选择要导出的数据')
        return
      }
      const rows = selected.map(r => ({
        '部门编号': r.code || '',
        '部门名称': r.name || '',
        '部门描述': r.desc || '',
        '部门负责人/班组长': r.leader || '',
        '员工数': r.userCount ?? '',
        '启用状态': r.statusText || '',
      }))
      const ws = XLSX.utils.json_to_sheet(rows)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '部门')
      const date = new Date().toISOString().slice(0, 10)
      XLSX.writeFile(wb, `部门_导出_${date}.xlsx`)
    },
    async loadUsersForSelect() {
      try {
        this.userLoading = true
        const res = await listUsers()
        const list = Array.isArray(res?.data?.data) ? res.data.data : []
        this.userOptions = list.map(u => ({
          value: u.userId ?? u.id ?? u.uid,
          label: `${u.realName || u.username || ''}${(u.userCode ? ' · ' + String(u.userCode).replace(/_/g, '') : '')}`.trim(),
        }))
      } finally { this.userLoading = false }
    }
  }
}
</script>

<style scoped>
.department-management { padding: 20px; background-color: #f5f7fa; }
.title-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.title-section h2 { font-size: 20px; font-weight: bold; }
.controls-section { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 20px; background-color: #fff; border-radius: 8px; margin-bottom: 20px; align-items: center; }
.filters { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-item label { font-size: 14px; white-space: nowrap; }
.filter-item input, .filter-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; width: 150px; }
.actions { display: flex; gap: 10px; }
.btn-primary { background-color: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background-color: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.table-section { background-color: #fff; padding: 20px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; }
th { background-color: #f8f9fa; }
.link-style { color: #409eff; cursor: pointer; }
.status-enable { color: #2eaa3b; }
.status-disable { color: #f44336; }
.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; background-color: #fff; padding: 10px 20px; border-radius: 8px; }
.footer-left { display: flex; align-items: center; gap: 8px; }
.pagination { display: flex; align-items: center; gap: 8px; }
.pagination button { padding: 6px 12px; border: 1px solid #dcdfe6; background-color: #fff; cursor: pointer; border-radius: 4px; }
.pagination button.active { background-color: #409eff; color: white; border-color: #409eff; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 4px; }

.dialog-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { width: 520px; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 6px 18px rgba(0,0,0,0.2); display: flex; flex-direction: column; }
.dialog-header { padding: 14px 16px; font-weight: 600; border-bottom: 1px solid #eee; }
.dialog-body { padding: 16px; }
.dialog-footer { padding: 12px 16px; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #eee; }
.form-row { margin-bottom: 12px; display: flex; align-items: center; gap: 10px; }
.form-row label { width: 120px; text-align: right; color: #606266; }
.form-row input, .form-row select { flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; }
.req { color: #f56c6c; margin-left: 4px; }
.err { color: #f56c6c; font-size: 12px; margin-left: 120px; margin-top: -6px; }

.drawer-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.2); z-index: 1000; }
.drawer { position: absolute; top: 0; right: 0; height: 100%; width: 520px; background: #fff; box-shadow: -2px 0 12px rgba(0,0,0,0.12); display: flex; flex-direction: column; }
.drawer-header { display: flex; justify-content: space-between; align-items: center; padding: 14px 16px; border-bottom: 1px solid #eee; font-weight: 600; }
.drawer-body { padding: 16px; overflow: auto; }
.detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
.item { background: #fafafa; border: 1px solid #f0f0f0; border-radius: 6px; padding: 10px 12px; }
.item-span { grid-column: 1 / -1; }
.label { font-size: 12px; color: #909399; margin-bottom: 6px; }
.value { font-size: 14px; color: #303133; }

.drawer-actions { display: flex; align-items: center; gap: 8px; position: relative; }
.more { width: 28px; height: 28px; border-radius: 50%; background: #f5f7fa; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 18px; line-height: 1; }
.menu { position: absolute; top: 34px; right: 72px; background: #fff; border: 1px solid #eee; box-shadow: 0 4px 10px rgba(0,0,0,0.12); border-radius: 8px; padding: 6px 0; width: 120px; z-index: 10; }
.menu-item { padding: 8px 12px; cursor: pointer; }
.menu-item:hover { background: #f5f7fa; }
.menu-item.danger { color: #f56c6c; }
</style>
